package online.inote.dic.common.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * Desc: IP 工具类
 * </p>
 *
 * @author XQF SUI
 * @created 2018年10月9日 下午2:38:45
 * @version 1.0
 */
public class IPUtils {
	
	private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

	/**
	 * <p>
	 * Desc: 获取本机IP
	 * </p>
	 *
	 * @author XQF SUI
	 * @created 2018年10月9日 下午2:38:45
	 * @return 
	 */
	public static String getLocalhostAddress() {
		try {
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
				
				if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
					continue;
				} else {
					Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
					
					while (addresses.hasMoreElements()) {
						ip = addresses.nextElement();
						
						if (ip != null && ip instanceof Inet4Address) {
							return ip.getHostAddress();
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("IP地址获取失败", e);
		}
		
		return "";
	}
}